<template>
  <el-dialog :visible.sync="visible" title="选择地图位置" width="800px" @open="initMap" append-to-body>
    <div style="margin-bottom: 10px; display: flex; align-items: center;">
      <el-input v-model="searchText" placeholder="请输入地址进行搜索" style="width: 300px; margin-right: 8px;" @keyup.enter.native="searchLocation" />
      <el-button @click="searchLocation">搜索</el-button>
    </div>
    <div id="mapContainer" style="width:100%;height:400px;"></div>
    <div style="margin: 10px 0; color: #666;">当前地址：{{ currentAddress }}</div>
    <div slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'MapDialog',
  props: {
    value: Boolean,
    position: String // "lng,lat"
  },
  data() {
    return {
      visible: this.value,
      map: null,
      marker: null,
      lnglat: this.position ? this.position.split(',').map(Number) : [116.397428, 39.90923], // 默认北京
      mapLoaded: false,
      searchText: '',
      geocoder: null,
      currentAddress: '',
    };
  },
  watch: {
    value: {
      handler(val) {
        this.visible = val;
        if (val && !this.mapLoaded) {
          this.$nextTick(this.initMap);
        }
      },
      immediate: true,
    },
    visible(val) {
      this.$emit('input', val);
      if (!val) {
        this.mapLoaded = false;
        this.map = null;
        this.marker = null;
        this.geocoder = null;
      }
    },
    position(val) {
      if (val) {
        this.lnglat = val.split(',').map(Number);
        if (this.marker) {
          this.marker.setPosition(this.lnglat);
          this.map.setCenter(this.lnglat);
          this.reverseGeocode(this.lnglat);
        }
      }
    }
  },
  created() {
    // console.log(this.mapLoaded, 62);
    // this.initMap();
  },
  methods: {
    initMap() {
      console.log(this.mapLoaded, 64);
      if (this.mapLoaded) return;
      if (!window.AMap) {
        const script = document.createElement('script');
        script.src = 'https://webapi.amap.com/maps?v=2.0&key=68563f94a9ebb3885ab4fbdec114ac18&plugin=AMap.Geocoder';
        script.onload = this.renderMap;
        document.body.appendChild(script);
      } else {
        this.renderMap();
      }
    },
    renderMap() {
      this.map = new window.AMap.Map('mapContainer', {
        center: this.lnglat,
        zoom: 15,
      });
      this.marker = new window.AMap.Marker({
        position: this.lnglat,
        draggable: true,
      });
      this.map.add(this.marker);
      this.map.on('click', (e) => {
        this.marker.setPosition([e.lnglat.lng, e.lnglat.lat]);
        this.lnglat = [e.lnglat.lng, e.lnglat.lat];
        this.reverseGeocode(this.lnglat);
      });
      this.marker.on('dragend', (e) => {
        this.lnglat = [e.lnglat.lng, e.lnglat.lat];
        this.reverseGeocode(this.lnglat);
      });
      // 初始化地理编码插件
      window.AMap.plugin('AMap.Geocoder', () => {
        this.geocoder = new window.AMap.Geocoder();
        this.reverseGeocode(this.lnglat);
      });
      this.mapLoaded = true;
    },
    searchLocation() {
      if (!this.searchText || !this.geocoder) return;
      this.geocoder.getLocation(this.searchText, (status, result) => {
        if (status === 'complete' && result.geocodes && result.geocodes.length > 0) {
          const location = result.geocodes[0].location;
          this.lnglat = [location.lng, location.lat];
          this.map.setCenter(this.lnglat);
          this.marker.setPosition(this.lnglat);
          this.reverseGeocode(this.lnglat);
        } else {
          this.$message.error('未找到该地址');
        }
      });
    },
    reverseGeocode(lnglat) {
      if (!this.geocoder) return;
      this.geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.currentAddress = result.regeocode.formattedAddress;
        } else {
          this.currentAddress = '';
        }
      });
    },
    confirm() {
      this.$emit('select', this.lnglat.join(','), this.currentAddress);
      this.visible = false;
    }
  }
};
</script> 